#!/bin/bash
# =====================================
# 作者：老曹  QQ:1484743
# 版权声明：本程序为个人原创、开源程序，禁止用于任何违法用途，任何违法用途均与作者无关。
# 仅限学习交流，转载请注明出处。如需商用请联系作者。
# =====================================

CONFIG_FILE="./backup_config.conf"
CRON_TAG="# FILE_BACKUP_SYSTEM_AUTO"
SCRIPT_PATH="$(readlink -f "$0")"

# 读取配置
load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"
    else
        FTP_HOST=""
        FTP_PORT=""
        FTP_USER=""
        FTP_PASS=""
        FTP_PATH=""
        BACKUP_SRC=""
        KEEP_LATEST=""
    fi
}

# 保存配置
save_config() {
    cat > "$CONFIG_FILE" <<EOF
FTP_HOST="$FTP_HOST"
FTP_PORT="$FTP_PORT"
FTP_USER="$FTP_USER"
FTP_PASS="$FTP_PASS"
FTP_PATH="$FTP_PATH"
BACKUP_SRC="$BACKUP_SRC"
KEEP_LATEST="$KEEP_LATEST"
EOF
}

# 配置菜单
config_menu() {
    echo "===== 配置信息管理 ====="
    local show_host=${FTP_HOST:-未配置}
    local show_port=${FTP_PORT:-未配置}
    local show_user=${FTP_USER:-未配置}
    local show_pass=${FTP_PASS:-未配置}
    local show_path=${FTP_PATH:-未配置}
    local show_src=${BACKUP_SRC:-未配置}
    local show_keep=${KEEP_LATEST:-未配置}
    read -p "FTP地址 [$show_host]: " input
    FTP_HOST=${input:-$FTP_HOST}
    read -p "FTP端口 [$show_port]: " input
    FTP_PORT=${input:-$FTP_PORT}
    read -p "FTP账户 [$show_user]: " input
    FTP_USER=${input:-$FTP_USER}
    read -p "FTP密码 [$show_pass]: " input
    FTP_PASS=${input:-$FTP_PASS}
    read -p "FTP路径 [$show_path]: " input
    FTP_PATH=${input:-$FTP_PATH}
    read -p "需要备份的本地路径 [$show_src]: " input
    BACKUP_SRC=${input:-$BACKUP_SRC}
    read -p "保留几份最新的备份文件 [$show_keep]: " input
    KEEP_LATEST=${input:-$KEEP_LATEST}
    save_config
    echo "配置信息已保存！"
}

# 检查并自动安装lftp
check_and_install_lftp() {
    if ! command -v lftp >/dev/null 2>&1; then
        echo "检测到系统未安装lftp，正在尝试自动安装..."
        if command -v apt >/dev/null 2>&1; then
            sudo apt update && sudo apt install -y lftp
        elif command -v yum >/dev/null 2>&1; then
            sudo yum install -y lftp
        else
            echo "未检测到支持的包管理器（apt或yum），请手动安装lftp后再运行本脚本。"
            exit 1
        fi
        if ! command -v lftp >/dev/null 2>&1; then
            echo "lftp 安装失败，请手动安装后重试。"
            exit 1
        fi
    fi
}

# 动态等待动画函数
show_waiting() {
    local i=0
    local dots=""
    while :; do
        case $((i % 4)) in
            0) dots="   " ;;
            1) dots=".  " ;;
            2) dots=".. " ;;
            3) dots="..." ;;
        esac
        echo -ne "正在运行中，请稍等$dots\033[K\r"
        sleep 0.5
        ((i++))
    done
}

# 执行备份
do_backup() {
    check_and_install_lftp
    load_config
    if [ -z "$FTP_HOST" ] || [ -z "$FTP_PORT" ] || [ -z "$FTP_USER" ] || [ -z "$FTP_PASS" ] || [ -z "$FTP_PATH" ] || [ -z "$BACKUP_SRC" ]; then
        echo "请先完善配置信息！"
        return
    fi
    if [ ! -d "$BACKUP_SRC" ] && [ ! -f "$BACKUP_SRC" ]; then
        echo "备份路径不存在：$BACKUP_SRC"
        return
    fi
    show_waiting &
    WAIT_PID=$!
    BACKUP_FILE="backup_$(date +%Y%m%d_%H%M%S).tar.gz"
    tar -czf "$BACKUP_FILE" "$BACKUP_SRC" 2>/dev/null
    curl -s -T "$BACKUP_FILE" --ftp-create-dirs -u "$FTP_USER:$FTP_PASS" "ftp://$FTP_HOST:$FTP_PORT/$FTP_PATH/$BACKUP_FILE"
    CURL_STATUS=$?
    if [ $CURL_STATUS -eq 0 ]; then
        rm -f "$BACKUP_FILE"
        # 自动清理FTP上旧备份文件
        if [ -n "$KEEP_LATEST" ] && [[ "$KEEP_LATEST" =~ ^[0-9]+$ ]] && [ "$KEEP_LATEST" -gt 0 ]; then
            lftp -u "$FTP_USER","$FTP_PASS" -p "$FTP_PORT" "$FTP_HOST" <<EOF
set ssl:verify-certificate no
cd "$FTP_PATH"
cls -1 backup_*.tar.gz > /tmp/ftp_backup_filelist.txt
bye
EOF
            mapfile -t FILES < <(grep -v '^$' /tmp/ftp_backup_filelist.txt | sort)
            TOTAL_FILES=${#FILES[@]}
            if [ "$TOTAL_FILES" -gt "$KEEP_LATEST" ]; then
                DEL_COUNT=$(($TOTAL_FILES - $KEEP_LATEST))
                for ((i=0; i<$DEL_COUNT; i++)); do
                    OLD_FILE="${FILES[$i]}"
                    lftp -u "$FTP_USER","$FTP_PASS" -p "$FTP_PORT" "$FTP_HOST" <<EOF
set ssl:verify-certificate no
cd "$FTP_PATH"
rm "$OLD_FILE"
bye
EOF
                done
            fi
            rm -f /tmp/ftp_backup_filelist.txt
        fi
        kill $WAIT_PID
        wait $WAIT_PID 2>/dev/null
        echo -ne "\033[K\r"
        echo "备份成功！"
    else
        kill $WAIT_PID
        wait $WAIT_PID 2>/dev/null
        echo -ne "\033[K\r"
        if [ $CURL_STATUS -eq 6 ]; then
            echo "备份失败！原因：无法连接到FTP服务器。"
        elif [ $CURL_STATUS -eq 7 ]; then
            echo "备份失败！原因：无法连接到FTP服务器（端口或网络问题）。"
        elif [ $CURL_STATUS -eq 67 ]; then
            echo "备份失败！原因：FTP认证失败（用户名或密码错误）。"
        else
            echo "备份失败！curl错误码：$CURL_STATUS，可能为FTP连接、认证或路径错误。"
        fi
        return
    fi
}

# 检查自动备份是否已开启
is_auto_backup_enabled() {
    crontab -l 2>/dev/null | grep -q "$CRON_TAG"
}

# 开启自动备份
enable_auto_backup() {
    is_auto_backup_enabled && { echo "自动备份已开启！"; return; }
    read -p "请输入每多少小时备份一次（默认12小时）: " input
    BACKUP_INTERVAL=${input:-12}
    if ! [[ "$BACKUP_INTERVAL" =~ ^[0-9]+$ ]] || [ "$BACKUP_INTERVAL" -le 0 ]; then
        echo "输入无效，已使用默认12小时。"
        BACKUP_INTERVAL=12
    fi
    (crontab -l 2>/dev/null; echo "0 */$BACKUP_INTERVAL * * * bash \"$SCRIPT_PATH\" --auto $CRON_TAG") | crontab -
    echo "自动备份已开启，每$BACKUP_INTERVAL小时执行一次。"
}

# 关闭自动备份
disable_auto_backup() {
    if ! is_auto_backup_enabled; then
        echo "自动备份未开启。"
        return
    fi
    crontab -l 2>/dev/null | grep -v "$CRON_TAG" | crontab -
    echo "自动备份已关闭。"
}

# 自动备份菜单
auto_backup_menu() {
    is_auto_backup_enabled && status="已开启" || status="未开启"
    echo "===== 自动备份管理（当前：$status）====="
    echo "1. 开启自动备份"
    echo "2. 关闭自动备份"
    echo "0. 返回主菜单"
    read -p "请选择操作: " choice
    case $choice in
        1) enable_auto_backup ;;
        2) disable_auto_backup ;;
        0) return ;;
        *) echo "无效选择，请重新输入！" ;;
    esac
}

# 主菜单
main_menu() {
    load_config
    while true; do
        echo "===== FTP文件备份系统 ====="
        echo "1. 配置信息管理"
        echo "2. 手动执行备份"
        echo "3. 自动备份管理"
        echo "4. 查看当前配置"
        echo "0. 退出"
        read -p "请选择操作: " choice
        case $choice in
            1) config_menu ;;
            2) do_backup ;;
            3) auto_backup_menu ;;
            4)
                load_config
                echo "===== 当前配置信息 ====="
                echo "FTP地址: ${FTP_HOST:-未配置}"
                echo "FTP端口: ${FTP_PORT:-未配置}"
                echo "FTP账户: ${FTP_USER:-未配置}"
                echo "FTP密码: ${FTP_PASS:-未配置}"
                echo "FTP路径: ${FTP_PATH:-未配置}"
                echo "需要备份的本地路径: ${BACKUP_SRC:-未配置}"
                echo "保留几份最新的备份文件: ${KEEP_LATEST:-未配置}"
                ;;
            0) exit 0 ;;
            *) echo "无效选择，请重新输入！" ;;
        esac
        echo
    done
}

# 支持crontab自动执行
if [ "$1" == "--auto" ]; then
    do_backup
    exit 0
fi

main_menu 